<template>
  <Dialog
    :title="dialogTitle"
          v-model="dialogVisible"
    :fullscreen="false"
    :fullscreen0="2">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item label="房屋中文名" prop="nameZhCn">
        <el-input v-model="formData.nameZhCn" placeholder="请输入房屋中文名" />
      </el-form-item>
      <el-form-item label="房屋英文名" prop="nameEnUs">
        <el-input v-model="formData.nameEnUs" placeholder="请输入房屋英文名" />
      </el-form-item>
      <el-form-item label="房屋图片" prop="showImages">
        <UploadImgs :file-size="12" :limit="12" v-model="formData.showImages" />
      </el-form-item>
      <el-form-item label="房屋视频" prop="showVideos">
        <UploadFile :file-size="128" :limit="12" :file-type="['mp4', 'mov', 'flv']" v-model="formData.showVideos" />
      </el-form-item>
      <el-form-item label="热门推荐" prop="isHot">
        <el-radio-group v-model="formData.isHot">
          <el-radio label="是" :value="true"/>
          <el-radio label="否" :value="false"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="最新楼盘" prop="isLatest">
        <el-radio-group v-model="formData.isLatest">
          <el-radio label="是" :value="true"/>
          <el-radio label="否" :value="false"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="主力户型中文" prop="mainHouseTypeZhCn">
        <el-input v-model="formData.mainHouseTypeZhCn" placeholder="请输入主力户型中文" />
      </el-form-item>
      <el-form-item label="主力户型英文" prop="mainHouseTypeEnUs">
        <el-input v-model="formData.mainHouseTypeEnUs" placeholder="请输入主力户型英文" />
      </el-form-item>
      <el-form-item label="最低价格" prop="priceMin">
        <el-input-number style="width: 100%" :min="0.01" v-model="formData.priceMin" placeholder="请输入最低价格" />
      </el-form-item>
      <el-form-item label="最高价格" prop="priceMax">
        <el-input-number style="width: 100%" :min="0.02" v-model="formData.priceMax" placeholder="请输入最高价格" />
      </el-form-item>
      <el-form-item label="参考总价" prop="totalAmount">
        <Editor v-model="formData.totalAmount" height="100px" />
      </el-form-item>
      <el-form-item label="中文标签" prop="tagsZhCn">
        <el-select
          v-model="formData.tagsZhCn"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="请填写中文标签">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_APARTMENT_CHINA_TAG)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="英文标签" prop="tagsEnUs">
        <el-select
          v-model="formData.tagsEnUs"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="请填写英文标签">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_APARTMENT_ENGLISH_TAG)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="中文亮点" prop="projectLightZhCn">
        <el-select
          v-model="formData.projectLightZhCn"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="请填写中文亮点">
          <el-option label="无" value="无"/>
        </el-select>
      </el-form-item>
      <el-form-item label="英文亮点" prop="projectLightEnUs">
        <el-select
          v-model="formData.projectLightEnUs"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="请填写英文亮点">
          <el-option label="无" value="无"/>
        </el-select>
      </el-form-item>
      <el-form-item label="项目类型" prop="projectType">
        <el-select
          v-model="formData.projectType"
          placeholder="请选择项目类型">
          <el-option v-for="dict in dictList" :key="dict.id" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="项目进度(中)" prop="projectProgressZhCn">
<!--        <el-input v-model="formData.projectProgressZhCn" placeholder="请输入项目进度（中文）" />-->
        <el-select
          v-model="formData.projectProgressZhCn"
          placeholder="请选择项目进度">
          <el-option
            v-for="item in projects"
            :key="item.id"
            :label="item.labelZhCn"
            :value="item.labelZhCn"/>
        </el-select>
      </el-form-item>
      <el-form-item label="项目进度(英)" prop="projectProgressEnUs">
<!--        <el-input v-model="formData.projectProgressEnUs" placeholder="请输入项目进度（英文）" />-->
        <el-select
          v-model="formData.projectProgressEnUs"
          placeholder="请选择项目进度">
          <el-option
            v-for="item in projects"
            :key="item.id"
            :label="item.labelEnUs"
            :value="item.labelEnUs"/>
        </el-select>
      </el-form-item>
      <el-form-item label="完工时间" prop="completionTime">
        <el-date-picker
          v-model="formData.completionTime"
          type="month"
          value-format="YYYY-MM-DD"
          placeholder="选择完工时间"
        />
      </el-form-item>
      <el-form-item label="建筑商(中)" prop="builderZhCn">
        <el-input v-model="formData.builderZhCn" placeholder="请输入建筑商中文名" />
      </el-form-item>
      <el-form-item label="建筑商(英)" prop="builderEnUs">
        <el-input v-model="formData.builderEnUs" placeholder="请输入建筑商英文名" />
      </el-form-item>
      <el-form-item label="设计师(中)" prop="designerZhCn">
        <el-input v-model="formData.designerZhCn" placeholder="请输入设计师中文名" />
      </el-form-item>
      <el-form-item label="设计师(英)" prop="designerEnUs">
        <el-input v-model="formData.designerEnUs" placeholder="请输入设计师英文名" />
      </el-form-item>
      <el-form-item label="关联资讯" prop="glzx">
        <el-select v-model="formData.infoIds" multiple filterable placeholder="请选择关联资讯">
          <el-option
            v-for="item in infos"
            :key="item.id"
            :label="item.title"
            :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="经纬度坐标" prop="point">
<!--        <Map ref="selfMapRef" @confirm-map-address="confirmMapAddress" style="width: 100%"/>-->
        <el-input v-model="formData.point" placeholder="请输入经纬度坐标" />
      </el-form-item>
      <el-form-item label="定位详情" prop="pointDetail">
        <el-input v-model="formData.pointDetail" placeholder="请输入定位详情" />
      </el-form-item>
      <el-form-item label="市区" prop="locationIds" style="width: 100%;">
        <el-cascader
          v-model="formData.locationIds"
          :options="openedCityTree"
          :props="{ checkStrictly: true, label: 'name', value: 'id' }"
          filterable/>
      </el-form-item>
      <el-form-item label="内容中文详情" prop="contentZhCn">
        <Editor v-model="formData.contentZhCn" height="600px" />
      </el-form-item>
      <el-form-item label="内容英文详情" prop="contentEnUs">
        <Editor v-model="formData.contentEnUs" height="600px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ApartmentApi, ApartmentVO } from '@/api/business/apartment'
import Map from "@/views/business/map/index.vue";
import {InfoApi} from "@/api/business/info";
import {OpenedCityApi} from "@/api/business/openedcity";
import {handleTree} from "@/utils/tree";
import {BizDictTypeApi} from "@/api/business/dicttype";
import {DICT_TYPE, getIntDictOptions, getStrDictOptions} from "@/utils/dict";

/** 楼盘/公寓 表单 */
defineOptions({ name: 'ApartmentForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  nameZhCn: undefined,
  nameEnUs: undefined,
  showImages: undefined,
  showVideos: undefined,
  mainHouseTypeZhCn: undefined,
  mainHouseTypeEnUs: undefined,
  priceMin: undefined,
  priceMax: undefined,
  tagsZhCn: undefined,
  tagsEnUs: undefined,
  projectType: undefined,
  projectProgressZhCn: undefined,
  projectProgressEnUs: undefined,
  completionTime: undefined,
  builderZhCn: undefined,
  builderEnUs: undefined,
  designerZhCn: undefined,
  designerEnUs: undefined,
  contentZhCn: undefined,
  contentEnUs: undefined,
  provinceId: undefined,
  cityId: undefined,
  countyId: undefined,
  point: undefined,
  pointDetail: undefined,
  location: undefined,
  locationIds: undefined,
  infoIds: undefined,
  isHot: undefined,
  isLatest: undefined,
  projectLightZhCn: undefined,
  projectLightEnUs: undefined,
  totalAmount: undefined,
})
const formRules = reactive({
  nameZhCn: [{ required: true, message: '房屋中文名不能为空', trigger: 'blur' }],
  nameEnUs: [{ required: true, message: '房屋英文名不能为空', trigger: 'blur' }],
  showImages: [{ required: true, message: '房屋图片不能为空', trigger: 'blur' }],
  /*showVideos: [{ required: true, message: '房屋视频不能为空', trigger: 'blur' }],*/
  mainHouseTypeZhCn: [{ required: true, message: '主力户型中文不能为空', trigger: 'blur' }],
  mainHouseTypeEnUs: [{ required: true, message: '主力户型英文不能为空', trigger: 'blur' }],
  /*tagsZhCn: [{ required: true, message: '中文标签不能为空', trigger: 'blur' }],
  tagsEnUs: [{ required: true, message: '英文标签不能为空', trigger: 'blur' }],*/
  projectType: [{ required: true, message: '项目类型不能为空', trigger: 'blur' }],
  projectProgressZhCn: [{ required: true, message: '项目进度（中文）不能为空', trigger: 'blur' }],
  projectProgressEnUs: [{ required: true, message: '项目进度（英文）不能为空', trigger: 'blur' }],
  /*completionTime: [{ required: true, message: '完工时间不能为空', trigger: 'blur' }],
  builderZhCn: [{ required: true, message: '建筑商中文名不能为空', trigger: 'blur' }],
  builderEnUs: [{ required: true, message: '建筑商英文名不能为空', trigger: 'blur' }],
  designerZhCn: [{ required: true, message: '设计师中文名不能为空', trigger: 'blur' }],
  designerEnUs: [{ required: true, message: '设计师英文名不能为空', trigger: 'blur' }],*/
  contentZhCn: [{ required: true, message: '内容中文详情不能为空', trigger: 'blur' }],
  contentEnUs: [{ required: true, message: '内容英文详情不能为空', trigger: 'blur' }],
  point: [{ required: true, message: '坐标点不能为空', trigger: 'blur' }],
  pointDetail: [{ required: true, message: '定位详情不能为空', trigger: 'blur' }],
  locationIds: [{ required: true, message: '市区不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

const handleClose = async (done) => {
  await message.confirm(('确认关闭窗口？'));
  dialogVisible.value = false
}
const dictList = ref() // 弹窗的是否展示
const getDictDataList = async (id: number) => {
  dictList.value = await BizDictTypeApi.getBizDictDataByTypeId(id)
}

const projects = ref() // 树形结构
/** 获得已开通城市树 */
const getProjects = async () => {
  projects.value = await BizDictTypeApi.getBizDictDataByTypeId(5)
}

const infos = ref() // 树形结构
/** 获得已开通城市树 */
const getInfos = async () => {
  infos.value = await InfoApi.getAllInfo()
}

const openedCityTree = ref() // 树形结构
/** 获得已开通城市树 */
const getOpenedCityTree = async () => {
  openedCityTree.value = []
  const data = await OpenedCityApi.getOpenedCityList()
  openedCityTree.value = handleTree(data, 'id', 'parentId')
}

/** 打开弹窗 */
const confirmMapAddress = async (addressInfo) => {
  formData.value.pointDetail = addressInfo.address
  formData.value.point = addressInfo.longitude + ',' + addressInfo.latitude
  formData.value.location = [addressInfo.province, addressInfo.city, addressInfo.district]
}

/** 添加/修改操作 */
const selfMapRef = ref()
const openMap = (longitude: number, latitude: number, address: string) => {
  selfMapRef.value.init(longitude, latitude, address)
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  await getOpenedCityTree()
  await getInfos()
  await getDictDataList(2)
  await getProjects()
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ApartmentApi.getApartment(id)

      let locations = formData.value.point.split(',')
      openMap(locations[0], locations[1], formData.value.pointDetail)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ApartmentVO
    if (formType.value === 'create') {
      await ApartmentApi.createApartment(data)
      message.success(t('common.createSuccess'))
    } else {
      await ApartmentApi.updateApartment(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    nameZhCn: undefined,
    nameEnUs: undefined,
    showImages: undefined,
    showVideos: undefined,
    mainHouseTypeZhCn: undefined,
    mainHouseTypeEnUs: undefined,
    priceMin: undefined,
    priceMax: undefined,
    tagsZhCn: undefined,
    tagsEnUs: undefined,
    projectType: undefined,
    projectProgressZhCn: undefined,
    projectProgressEnUs: undefined,
    completionTime: undefined,
    builderZhCn: undefined,
    builderEnUs: undefined,
    designerZhCn: undefined,
    designerEnUs: undefined,
    contentZhCn: undefined,
    contentEnUs: undefined,
    provinceId: undefined,
    cityId: undefined,
    countyId: undefined,
    point: undefined,
    pointDetail: undefined,
    location: undefined,
    locationIds: undefined,
    infoIds: undefined,
    isHot: undefined,
    isLatest: undefined,
    projectLightZhCn: undefined,
    projectLightEnUs: undefined,
    totalAmount: undefined,
  }
  formRef.value?.resetFields()
}
</script>
